package com.tt.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tt.bean.Comment;
import com.tt.bean.SaySome;
import com.tt.dao.CircleOfFriendsDaoImpl;
@Service
public class CircleOfFriendServiceImpl implements CircleOfFriendService {
	@Autowired
	CircleOfFriendsDaoImpl circleOfFriendsDaoImpl;
	
	@Override
	public void sendMessage(SaySome saySome) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();	
		saySome.setTime(sdf.format(date));
		circleOfFriendsDaoImpl.sendMessage(saySome);
	}

	@Override
	public JSONArray selectSaySomething(long uid,long page) {
		HashMap<String, Long> hm = new HashMap<>();
		page=page*10-10;
		hm.put("uid", uid);
		hm.put("page", page);
		JSONArray json = new JSONArray();
		List<SaySome> list = circleOfFriendsDaoImpl.selectSaySomething(hm);
		for (SaySome a : list) {
			JSONObject jo = new JSONObject();
			jo.put("id", a.getId());
			hm.put("id", a.getId());
			long count = circleOfFriendsDaoImpl.selectCount(hm);
			jo.put("count", count);
			int good = circleOfFriendsDaoImpl.selectGood(hm);
			if(good != 0){
				jo.put("good", 1);
			}else{
				jo.put("good", 0);
			}
			List<Comment> listComment = circleOfFriendsDaoImpl.selectComment(hm);
			JSONArray jsonComment = new JSONArray();
			for (Comment comment : listComment) {
				JSONObject joComment = new JSONObject();
				joComment.put("name", comment.getName());
				joComment.put("cid", comment.getCid());
				joComment.put("msg", comment.getMsg());
				joComment.put("time", comment.getTime().substring(0, comment.getTime().length()-2));
				joComment.put("uid", comment.getUid());
				jsonComment.put(joComment);
			}
			jo.put("comment", jsonComment);
			jo.put("name", a.getUsername());
			jo.put("imgUrl", a.getImgUrl());
			jo.put("photo", a.getPhoto());
			jo.put("msg", a.getMsg());
			jo.put("uid", a.getUid());
			jo.put("time", a.getTime().substring(0, a.getTime().length()-2));
			json.put(jo);
		}
		return json;
	}

	@Override
	public void giveGoodAjax(long uid, long id) {
		HashMap<String, Long> hm = new HashMap<>();
		hm.put("uid", uid);
		hm.put("id", id);
		circleOfFriendsDaoImpl.addGood(hm);
	}

	@Override
	public void removeGoodAjax(long uid, long id) {
		HashMap<String, Long> hm = new HashMap<>();
		hm.put("uid", uid);
		hm.put("id", id);
		circleOfFriendsDaoImpl.removeGood(hm);
	}

	@Override
	public String sendCommentAjax(Comment comment) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String time = sdf.format(date);
		comment.setTime(time);
		circleOfFriendsDaoImpl.sendCommentAjax(comment);
		return time;
	}

	
}
